import zmq
import struct

def subscriber():
    context = zmq.Context()
    socket = context.socket(zmq.SUB)
    socket.connect("tcp://localhost:5556")
    # socket.setsockopt(zmq.SUBSCRIBE, b"") # 订阅所有消息
    topic = b"test"
    socket.setsockopt(zmq.SUBSCRIBE, topic)

    try:
        while True:
            recv_data = socket.recv()
            msg = recv_data.split(b' ', 1)[1]
            index = msg.index(b':')
            count = struct.unpack('i', msg[index+1:])[0]
            print(f"订阅到 话题:{topic.decode()} -- 数据:{msg[0:index]}:{count}")
    except KeyboardInterrupt:
        print("Subscriber stopped.")
    finally:
        socket.close()
        context.term()

if __name__ == "__main__":
    subscriber()
    